import React, { useState, useEffect } from 'react';
import {
  Table,
  Card,
  Button,
  Space,
  Input,
  Select,
  DatePicker,
  Modal,
  Form,
  message,
  Popconfirm,
  Tag,
  Avatar,
  Tooltip,
  Badge,
  Drawer,
  Descriptions,
  Tabs,
  List,
  Typography,
  Row,
  Col,
  Statistic,
  Switch
} from 'antd';
import {
  SearchOutlined,
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  UserOutlined,
  MailOutlined,
  PhoneOutlined,
  CalendarOutlined,
  DollarOutlined,
  EyeOutlined,
  LockOutlined,
  UnlockOutlined,
  ExportOutlined,
  ReloadOutlined,
  FilterOutlined
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import type { TableProps } from 'antd';
import dayjs from 'dayjs';

const { Search } = Input;
const { Option } = Select;
const { RangePicker } = DatePicker;
const { Title, Text } = Typography;
// const { TabPane } = Tabs;

interface User {
  id: string;
  username: string;
  email: string;
  phone: string;
  realName: string;
  avatar?: string;
  status: 'active' | 'inactive' | 'locked';
  role: 'user' | 'vip' | 'admin';
  registrationDate: string;
  lastLoginDate: string;
  totalAssets: number;
  riskLevel: 'conservative' | 'moderate' | 'aggressive';
  kycStatus: 'pending' | 'approved' | 'rejected';
  loginCount: number;
  isOnline: boolean;
}

interface UserActivity {
  id: string;
  type: 'login' | 'transaction' | 'profile_update' | 'password_change';
  description: string;
  timestamp: string;
  ip?: string;
  device?: string;
}

const UserManagement: React.FC = () => {
  const [users, setUsers] = useState<User[]>([]);
  const [loading, setLoading] = useState(false);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [searchText, setSearchText] = useState('');
  const [statusFilter, setStatusFilter] = useState<string>('');
  const [roleFilter, setRoleFilter] = useState<string>('');
  const [dateRange, setDateRange] = useState<[dayjs.Dayjs, dayjs.Dayjs] | null>(null);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0
  });
  
  // 模态框状态
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [modalType, setModalType] = useState<'create' | 'edit'>('create');
  const [editingUser, setEditingUser] = useState<User | null>(null);
  const [form] = Form.useForm();
  
  // 用户详情抽屉
  const [detailDrawerVisible, setDetailDrawerVisible] = useState(false);
  const [selectedUser, setSelectedUser] = useState<User | null>(null);
  const [userActivities, setUserActivities] = useState<UserActivity[]>([]);

  // 加载用户数据
  useEffect(() => {
    loadUsers();
  }, [pagination.current, pagination.pageSize, searchText, statusFilter, roleFilter, dateRange]);

  const loadUsers = async () => {
    setLoading(true);
    try {
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 1000));
      
      const mockUsers: User[] = [
        {
          id: '1',
          username: 'zhangsan',
          email: 'zhangsan@example.com',
          phone: '13800138001',
          realName: '张三',
          avatar: '',
          status: 'active',
          role: 'vip',
          registrationDate: '2024-01-01',
          lastLoginDate: '2024-01-15 14:30:00',
          totalAssets: 1500000,
          riskLevel: 'moderate',
          kycStatus: 'approved',
          loginCount: 156,
          isOnline: true
        },
        {
          id: '2',
          username: 'lisi',
          email: 'lisi@example.com',
          phone: '13800138002',
          realName: '李四',
          status: 'active',
          role: 'user',
          registrationDate: '2024-01-02',
          lastLoginDate: '2024-01-14 09:15:00',
          totalAssets: 500000,
          riskLevel: 'conservative',
          kycStatus: 'approved',
          loginCount: 89,
          isOnline: false
        },
        {
          id: '3',
          username: 'wangwu',
          email: 'wangwu@example.com',
          phone: '13800138003',
          realName: '王五',
          status: 'locked',
          role: 'user',
          registrationDate: '2024-01-03',
          lastLoginDate: '2024-01-10 16:45:00',
          totalAssets: 200000,
          riskLevel: 'aggressive',
          kycStatus: 'pending',
          loginCount: 23,
          isOnline: false
        }
      ];
      
      setUsers(mockUsers);
      setPagination(prev => ({ ...prev, total: mockUsers.length }));
    } catch (error) {
      message.error('加载用户数据失败');
    } finally {
      setLoading(false);
    }
  };

  // 加载用户活动记录
  const loadUserActivities = async (userId: string) => {
    try {
      const mockActivities: UserActivity[] = [
        {
          id: '1',
          type: 'login',
          description: '用户登录',
          timestamp: '2024-01-15 14:30:00',
          ip: '192.168.1.100',
          device: 'Chrome/Windows'
        },
        {
          id: '2',
          type: 'transaction',
          description: '购买产品：稳健增长基金',
          timestamp: '2024-01-15 10:20:00'
        },
        {
          id: '3',
          type: 'profile_update',
          description: '更新个人资料',
          timestamp: '2024-01-14 16:45:00'
        }
      ];
      setUserActivities(mockActivities);
    } catch (error) {
      message.error('加载用户活动记录失败');
    }
  };

  // 表格列定义
  const columns: ColumnsType<User> = [
    {
      title: '用户信息',
      key: 'userInfo',
      width: 200,
      render: (_, record) => (
        <Space>
          <Badge dot={record.isOnline} color="green">
            <Avatar 
              src={record.avatar} 
              icon={<UserOutlined />}
              size="small"
            />
          </Badge>
          <div>
            <div style={{ fontWeight: 500 }}>{record.realName}</div>
            <div style={{ fontSize: 12, color: '#666' }}>@{record.username}</div>
          </div>
        </Space>
      )
    },
    {
      title: '联系方式',
      key: 'contact',
      width: 180,
      render: (_, record) => (
        <div>
          <div style={{ fontSize: 12 }}>
            <MailOutlined style={{ marginRight: 4 }} />
            {record.email}
          </div>
          <div style={{ fontSize: 12, marginTop: 2 }}>
            <PhoneOutlined style={{ marginRight: 4 }} />
            {record.phone}
          </div>
        </div>
      )
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status: string) => {
        const statusConfig = {
          active: { color: 'green', text: '正常' },
          inactive: { color: 'orange', text: '未激活' },
          locked: { color: 'red', text: '锁定' }
        };
        const config = statusConfig[status as keyof typeof statusConfig];
        return <Tag color={config.color}>{config.text}</Tag>;
      },
      filters: [
        { text: '正常', value: 'active' },
        { text: '未激活', value: 'inactive' },
        { text: '锁定', value: 'locked' }
      ]
    },
    {
      title: '角色',
      dataIndex: 'role',
      key: 'role',
      width: 80,
      render: (role: string) => {
        const roleConfig = {
          user: { color: 'blue', text: '普通用户' },
          vip: { color: 'gold', text: 'VIP用户' },
          admin: { color: 'purple', text: '管理员' }
        };
        const config = roleConfig[role as keyof typeof roleConfig];
        return <Tag color={config.color}>{config.text}</Tag>;
      },
      filters: [
        { text: '普通用户', value: 'user' },
        { text: 'VIP用户', value: 'vip' },
        { text: '管理员', value: 'admin' }
      ]
    },
    {
      title: '总资产',
      dataIndex: 'totalAssets',
      key: 'totalAssets',
      width: 120,
      render: (assets: number) => (
        <span style={{ fontWeight: 500 }}>
          ¥{(assets / 10000).toFixed(1)}万
        </span>
      ),
      sorter: (a, b) => a.totalAssets - b.totalAssets
    },
    {
      title: 'KYC状态',
      dataIndex: 'kycStatus',
      key: 'kycStatus',
      width: 100,
      render: (status: string) => {
        const statusConfig = {
          pending: { color: 'orange', text: '待审核' },
          approved: { color: 'green', text: '已通过' },
          rejected: { color: 'red', text: '已拒绝' }
        };
        const config = statusConfig[status as keyof typeof statusConfig];
        return <Tag color={config.color}>{config.text}</Tag>;
      }
    },
    {
      title: '注册时间',
      dataIndex: 'registrationDate',
      key: 'registrationDate',
      width: 120,
      render: (date: string) => dayjs(date).format('YYYY-MM-DD'),
      sorter: (a, b) => dayjs(a.registrationDate).unix() - dayjs(b.registrationDate).unix()
    },
    {
      title: '操作',
      key: 'actions',
      width: 200,
      fixed: 'right',
      render: (_, record) => (
        <Space size="small">
          <Tooltip title="查看详情">
            <Button 
              type="text" 
              icon={<EyeOutlined />} 
              size="small"
              onClick={() => handleViewUser(record)}
            />
          </Tooltip>
          <Tooltip title="编辑">
            <Button 
              type="text" 
              icon={<EditOutlined />} 
              size="small"
              onClick={() => handleEditUser(record)}
            />
          </Tooltip>
          <Tooltip title={record.status === 'locked' ? '解锁' : '锁定'}>
            <Button 
              type="text" 
              icon={record.status === 'locked' ? <UnlockOutlined /> : <LockOutlined />} 
              size="small"
              onClick={() => handleToggleUserStatus(record)}
            />
          </Tooltip>
          <Popconfirm
            title="确定要删除这个用户吗？"
            onConfirm={() => handleDeleteUser(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Tooltip title="删除">
              <Button 
                type="text" 
                icon={<DeleteOutlined />} 
                size="small"
                danger
              />
            </Tooltip>
          </Popconfirm>
        </Space>
      )
    }
  ];

  // 处理查看用户详情
  const handleViewUser = (user: User) => {
    setSelectedUser(user);
    setDetailDrawerVisible(true);
    loadUserActivities(user.id);
  };

  // 处理编辑用户
  const handleEditUser = (user: User) => {
    setEditingUser(user);
    setModalType('edit');
    form.setFieldsValue({
      ...user,
      registrationDate: dayjs(user.registrationDate)
    });
    setIsModalVisible(true);
  };

  // 处理创建用户
  const handleCreateUser = () => {
    setEditingUser(null);
    setModalType('create');
    form.resetFields();
    setIsModalVisible(true);
  };

  // 处理切换用户状态
  const handleToggleUserStatus = async (user: User) => {
    try {
      const newStatus = user.status === 'locked' ? 'active' : 'locked';
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 500));
      
      setUsers(prev => prev.map(u => 
        u.id === user.id ? { ...u, status: newStatus } : u
      ));
      
      message.success(`用户${newStatus === 'locked' ? '锁定' : '解锁'}成功`);
    } catch (error) {
      message.error('操作失败');
    }
  };

  // 处理删除用户
  const handleDeleteUser = async (userId: string) => {
    try {
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 500));
      
      setUsers(prev => prev.filter(u => u.id !== userId));
      message.success('删除用户成功');
    } catch (error) {
      message.error('删除用户失败');
    }
  };

  // 处理表单提交
  const handleFormSubmit = async (values: any) => {
    try {
      setLoading(true);
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 1000));
      
      if (modalType === 'create') {
        const newUser: User = {
          ...values,
          id: Date.now().toString(),
          registrationDate: values.registrationDate.format('YYYY-MM-DD'),
          lastLoginDate: '',
          loginCount: 0,
          isOnline: false
        };
        setUsers(prev => [newUser, ...prev]);
        message.success('创建用户成功');
      } else {
        setUsers(prev => prev.map(u => 
          u.id === editingUser?.id 
            ? { 
                ...u, 
                ...values,
                registrationDate: values.registrationDate.format('YYYY-MM-DD')
              } 
            : u
        ));
        message.success('更新用户成功');
      }
      
      setIsModalVisible(false);
      form.resetFields();
    } catch (error) {
      message.error('操作失败');
    } finally {
      setLoading(false);
    }
  };

  // 处理批量操作
  const handleBatchOperation = (operation: string) => {
    if (selectedRowKeys.length === 0) {
      message.warning('请选择要操作的用户');
      return;
    }
    
    Modal.confirm({
      title: `确定要${operation}选中的${selectedRowKeys.length}个用户吗？`,
      onOk: async () => {
        try {
          // 模拟API调用
          await new Promise(resolve => setTimeout(resolve, 1000));
          
          if (operation === '删除') {
            setUsers(prev => prev.filter(u => !selectedRowKeys.includes(u.id)));
          } else if (operation === '锁定') {
            setUsers(prev => prev.map(u => 
              selectedRowKeys.includes(u.id) ? { ...u, status: 'locked' as const } : u
            ));
          } else if (operation === '解锁') {
            setUsers(prev => prev.map(u => 
              selectedRowKeys.includes(u.id) ? { ...u, status: 'active' as const } : u
            ));
          }
          
          setSelectedRowKeys([]);
          message.success(`批量${operation}成功`);
        } catch (error) {
          message.error(`批量${operation}失败`);
        }
      }
    });
  };

  // 表格选择配置
  const rowSelection: TableProps<User>['rowSelection'] = {
    selectedRowKeys,
    onChange: setSelectedRowKeys,
    selections: [
      Table.SELECTION_ALL,
      Table.SELECTION_INVERT,
      Table.SELECTION_NONE
    ]
  };

  return (
    <div>
      {/* 页面标题和统计 */}
      <Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
        <Col span={6}>
          <Card>
            <Statistic
              title="总用户数"
              value={users.length}
              prefix={<UserOutlined />}
              valueStyle={{ color: '#3f8600' }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="活跃用户"
              value={users.filter(u => u.status === 'active').length}
              valueStyle={{ color: '#1890ff' }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="VIP用户"
              value={users.filter(u => u.role === 'vip').length}
              valueStyle={{ color: '#722ed1' }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="在线用户"
              value={users.filter(u => u.isOnline).length}
              valueStyle={{ color: '#fa8c16' }}
            />
          </Card>
        </Col>
      </Row>

      <Card>
        {/* 搜索和筛选栏 */}
        <div style={{ marginBottom: 16 }}>
          <Row gutter={[16, 16]}>
            <Col xs={24} sm={8} md={6}>
              <Search
                placeholder="搜索用户名、邮箱、手机号"
                value={searchText}
                onChange={(e) => setSearchText(e.target.value)}
                onSearch={loadUsers}
                enterButton={<SearchOutlined />}
              />
            </Col>
            <Col xs={12} sm={4} md={3}>
              <Select
                placeholder="状态"
                value={statusFilter}
                onChange={setStatusFilter}
                style={{ width: '100%' }}
                allowClear
              >
                <Option value="active">正常</Option>
                <Option value="inactive">未激活</Option>
                <Option value="locked">锁定</Option>
              </Select>
            </Col>
            <Col xs={12} sm={4} md={3}>
              <Select
                placeholder="角色"
                value={roleFilter}
                onChange={setRoleFilter}
                style={{ width: '100%' }}
                allowClear
              >
                <Option value="user">普通用户</Option>
                <Option value="vip">VIP用户</Option>
                <Option value="admin">管理员</Option>
              </Select>
            </Col>
            <Col xs={24} sm={8} md={6}>
              <RangePicker
                value={dateRange}
                onChange={(dates) => setDateRange(dates as [dayjs.Dayjs, dayjs.Dayjs] | null)}
                style={{ width: '100%' }}
                placeholder={['开始日期', '结束日期']}
              />
            </Col>
            <Col xs={24} md={6}>
              <Space>
                <Button icon={<ReloadOutlined />} onClick={loadUsers}>
                  刷新
                </Button>
                <Button icon={<FilterOutlined />}>
                  高级筛选
                </Button>
                <Button icon={<ExportOutlined />}>
                  导出
                </Button>
              </Space>
            </Col>
          </Row>
        </div>

        {/* 操作栏 */}
        <div style={{ marginBottom: 16, display: 'flex', justifyContent: 'space-between' }}>
          <Space>
            <Button 
              type="primary" 
              icon={<PlusOutlined />}
              onClick={handleCreateUser}
            >
              新增用户
            </Button>
            {selectedRowKeys.length > 0 && (
              <>
                <Button onClick={() => handleBatchOperation('锁定')}>
                  批量锁定
                </Button>
                <Button onClick={() => handleBatchOperation('解锁')}>
                  批量解锁
                </Button>
                <Button danger onClick={() => handleBatchOperation('删除')}>
                  批量删除
                </Button>
              </>
            )}
          </Space>
          <Text type="secondary">
            {selectedRowKeys.length > 0 && `已选择 ${selectedRowKeys.length} 项`}
          </Text>
        </div>

        {/* 用户表格 */}
        <Table<User>
          columns={columns}
          dataSource={users}
          rowKey="id"
          rowSelection={rowSelection}
          loading={loading}
          pagination={{
            ...pagination,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total, range) => 
              `第 ${range[0]}-${range[1]} 条/共 ${total} 条`,
            onChange: (page, pageSize) => {
              setPagination(prev => ({ ...prev, current: page, pageSize }));
            }
          }}
          scroll={{ x: 1200 }}
        />
      </Card>

      {/* 用户表单模态框 */}
      <Modal
        title={modalType === 'create' ? '新增用户' : '编辑用户'}
        open={isModalVisible}
        onCancel={() => setIsModalVisible(false)}
        footer={null}
        width={600}
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleFormSubmit}
        >
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="username"
                label="用户名"
                rules={[{ required: true, message: '请输入用户名' }]}
              >
                <Input placeholder="请输入用户名" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="realName"
                label="真实姓名"
                rules={[{ required: true, message: '请输入真实姓名' }]}
              >
                <Input placeholder="请输入真实姓名" />
              </Form.Item>
            </Col>
          </Row>
          
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="email"
                label="邮箱"
                rules={[
                  { required: true, message: '请输入邮箱' },
                  { type: 'email', message: '请输入有效的邮箱地址' }
                ]}
              >
                <Input placeholder="请输入邮箱" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="phone"
                label="手机号"
                rules={[{ required: true, message: '请输入手机号' }]}
              >
                <Input placeholder="请输入手机号" />
              </Form.Item>
            </Col>
          </Row>
          
          <Row gutter={16}>
            <Col span={8}>
              <Form.Item
                name="status"
                label="状态"
                rules={[{ required: true, message: '请选择状态' }]}
              >
                <Select placeholder="请选择状态">
                  <Option value="active">正常</Option>
                  <Option value="inactive">未激活</Option>
                  <Option value="locked">锁定</Option>
                </Select>
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                name="role"
                label="角色"
                rules={[{ required: true, message: '请选择角色' }]}
              >
                <Select placeholder="请选择角色">
                  <Option value="user">普通用户</Option>
                  <Option value="vip">VIP用户</Option>
                  <Option value="admin">管理员</Option>
                </Select>
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                name="riskLevel"
                label="风险偏好"
                rules={[{ required: true, message: '请选择风险偏好' }]}
              >
                <Select placeholder="请选择风险偏好">
                  <Option value="conservative">保守型</Option>
                  <Option value="moderate">稳健型</Option>
                  <Option value="aggressive">激进型</Option>
                </Select>
              </Form.Item>
            </Col>
          </Row>
          
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="totalAssets"
                label="总资产"
                rules={[{ required: true, message: '请输入总资产' }]}
              >
                <Input 
                  type="number" 
                  placeholder="请输入总资产" 
                  addonBefore="¥"
                />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="kycStatus"
                label="KYC状态"
                rules={[{ required: true, message: '请选择KYC状态' }]}
              >
                <Select placeholder="请选择KYC状态">
                  <Option value="pending">待审核</Option>
                  <Option value="approved">已通过</Option>
                  <Option value="rejected">已拒绝</Option>
                </Select>
              </Form.Item>
            </Col>
          </Row>
          
          {modalType === 'create' && (
            <Form.Item
              name="registrationDate"
              label="注册日期"
              rules={[{ required: true, message: '请选择注册日期' }]}
            >
              <DatePicker style={{ width: '100%' }} />
            </Form.Item>
          )}
          
          <Form.Item style={{ marginBottom: 0, textAlign: 'right' }}>
            <Space>
              <Button onClick={() => setIsModalVisible(false)}>
                取消
              </Button>
              <Button type="primary" htmlType="submit" loading={loading}>
                {modalType === 'create' ? '创建' : '更新'}
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>

      {/* 用户详情抽屉 */}
      <Drawer
        title="用户详情"
        placement="right"
        width={600}
        open={detailDrawerVisible}
        onClose={() => setDetailDrawerVisible(false)}
      >
        {selectedUser && (
          <Tabs 
            defaultActiveKey="basic"
            items={[
              {
                key: 'basic',
                label: '基本信息',
                children: (
                  <Descriptions column={1} bordered>
                    <Descriptions.Item label="用户名">{selectedUser.username}</Descriptions.Item>
                    <Descriptions.Item label="真实姓名">{selectedUser.realName}</Descriptions.Item>
                    <Descriptions.Item label="邮箱">{selectedUser.email}</Descriptions.Item>
                    <Descriptions.Item label="手机号">{selectedUser.phone}</Descriptions.Item>
                    <Descriptions.Item label="状态">
                      <Tag color={selectedUser.status === 'active' ? 'green' : 'red'}>
                        {selectedUser.status === 'active' ? '正常' : '锁定'}
                      </Tag>
                    </Descriptions.Item>
                    <Descriptions.Item label="角色">
                      <Tag color="blue">{selectedUser.role}</Tag>
                    </Descriptions.Item>
                    <Descriptions.Item label="风险偏好">{selectedUser.riskLevel}</Descriptions.Item>
                    <Descriptions.Item label="总资产">
                      ¥{(selectedUser.totalAssets / 10000).toFixed(1)}万
                    </Descriptions.Item>
                    <Descriptions.Item label="KYC状态">
                      <Tag color={selectedUser.kycStatus === 'approved' ? 'green' : 'orange'}>
                        {selectedUser.kycStatus}
                      </Tag>
                    </Descriptions.Item>
                    <Descriptions.Item label="注册时间">{selectedUser.registrationDate}</Descriptions.Item>
                    <Descriptions.Item label="最后登录">{selectedUser.lastLoginDate}</Descriptions.Item>
                    <Descriptions.Item label="登录次数">{selectedUser.loginCount}</Descriptions.Item>
                  </Descriptions>
                )
              },
              {
                key: 'activities',
                label: '活动记录',
                children: (
                  <List
                    dataSource={userActivities}
                    renderItem={(item) => (
                      <List.Item key={item.id}>
                        <List.Item.Meta
                          title={item.description}
                          description={
                            <Space direction="vertical" size={0}>
                              <Text type="secondary">{item.timestamp}</Text>
                              {item.ip && <Text type="secondary">IP: {item.ip}</Text>}
                              {item.device && <Text type="secondary">设备: {item.device}</Text>}
                            </Space>
                          }
                        />
                      </List.Item>
                    )}
                  />
                )
              }
            ]}
          />
        )}
      </Drawer>
    </div>
  );
};

export default UserManagement;